package com.csun.dsms.task;

import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.model.domain.YcAlert;
import com.csun.dsms.model.domain.YcDevice;
import com.csun.dsms.model.domain.YcDeviceData;
import com.csun.dsms.model.dto.yc.YcDataDto;
import com.csun.dsms.model.dto.yc.YcDeviceQueryDto;
import com.csun.dsms.model.dto.yc.YcRequestBean;
import com.csun.dsms.service.YcAlertService;
import com.csun.dsms.service.YcDeviceDataService;
import com.csun.dsms.service.YcDeviceService;
import com.csun.dsms.utils.DateUtil;
import com.csun.dsms.utils.SmsUtils;
import com.csun.dsms.utils.YcRequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@EnableScheduling
public class YcQueryDataTask {

    @Resource
    private RedisTemplate<String, String> redis;

    @Resource
    private YcDeviceDataService ycDeviceDataService;


    @Resource
    private YcDeviceService ycDeviceService;

    @Resource
    private YcAlertService ycAlertServiceImpl;

    @Scheduled(cron = "0 01 01 * * ?")
    public void delRadarDataTask(){
//        log.info("定时删除上个月的数据");
//        ycDeviceDataService.deleteBfDate();
    }

    /**
     * 每1小时执行一次
     */
    //0 0 0/2 * * ?
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void getToken(){
//        String url = "http://dust.0531yun.cn/api/getTokenByAcc?loginName=c230527zhcs&password=c230527zhcs";
//        String result = YcRequestUtil.doYcLogin(url);
//        ObjectMapper objectMapper = new ObjectMapper();
//        try {
//            ObjectNode jsonNodes = objectMapper.readValue(result, ObjectNode.class);
//            String token = jsonNodes.get("data").get("token").asText();
//            redis.opsForValue().set("ycToken", token);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
    }


    /**
     * 每5分钟执行一次
     * 查询报警数据出来
     */
    //0 0/5 * * * ?
    @Scheduled(cron = "0 0/5 * * * ?")
    public void queryAllDeviceData(){
//        dataList.forEach(item->{
//            long minute = (new Date().getTime() - item.getCreatedTime().getTime()) / (60 * 1000);
//            if (minute > 15){
//                addAlert(item.getNo(),0,"","设备离线报警");
//            }else if (item.getPm25()>80){
//                addAlert(item.getNo(),1,""+item.getPm25(),"PM2.5超上限报警");
//            }else if (item.getPm10()>70){
//                addAlert(item.getNo(),2,""+item.getPm10(),"PM10超上限报警");
//            }else if (item.getTsp()>80){
//                addAlert(item.getNo(),3,""+item.getTsp(),"TSP浓度超上限报警");
//            }
//        });

    }

    private void addAlert(String no,int type,String alertValue,String msg){
        //首先查询设备是否有报警
        YcDeviceQueryDto ycDeviceQueryDto = new YcDeviceQueryDto();
        ycDeviceQueryDto.setNo(no);
        ycDeviceQueryDto.setType(type);
        log.info("addAlert === 1  no "+no +" type: "+type);
        //同设备同类型报警 12小时只产生一个
        List<YcAlert> ycAlerts = ycAlertServiceImpl.query(ycDeviceQueryDto);
        long hour = 0;
        if (ycAlerts!=null && ycAlerts.size()>0){
            if (ycAlerts.get(0).getIsRead() == 0){
                hour = (new Date().getTime() - ycAlerts.get(0).getCreatedTime().getTime()) / (60 * 60 * 1000);
                log.info("addAlert === 2  hour : "+hour);
            }
        }

        if (hour > 12){
            log.info("addAlert === 3  addAlert "+no);
            //防止设备离线报警重复发送
            YcAlert ycAlert = new YcAlert();
            ycAlert.setNo(no);
            ycAlert.setIsRead(0);
            ycAlert.setAlertValue(alertValue);
            ycAlert.setCreatedTime(new Date());
            ycAlert.setType(type);
            ycAlert.setContent(msg);
            ycAlertServiceImpl.addAlert(ycAlert);
            // 查询设备
            YcDevice ycDevice = new YcDevice();
            ycDevice.setNo(no);
            List<YcDevice> ycDevices = ycDeviceService.query(ycDevice);
            if (ycDevices!=null && ycDevices.size()>0){
                SmsUtils smsUtils = new SmsUtils();
                JSONObject jsonObject = new JSONObject();
                String phoneSs = ycDevices.get(0).getPhone();
                if (phoneSs!=null){
                    if (phoneSs.length() ==11){
                        jsonObject.put("phone",phoneSs);
                        jsonObject.put("no",ycDevices.get(0).getNo());
                        jsonObject.put("content",msg);
                        jsonObject.put("location",ycDevices.get(0).getCompany()+" "+ycDevices.get(0).getLocation());
                        jsonObject.put("time", DateUtil.getNowTime());
                        smsUtils.sendMsg(phoneSs,jsonObject.toJSONString());
                        log.info("addAlert === 4  sendMsg : "+phoneSs);
                    }else{
                        String[] phoness = phoneSs.split(",");
                        for (int i = 0; i < phoness.length; i++) {
                            if (phoness[i].length() ==11){
                                jsonObject.put("phone",phoness[i]);
                                jsonObject.put("no",ycDevices.get(0).getNo());
                                jsonObject.put("content",msg);
                                jsonObject.put("location",ycDevices.get(0).getCompany()+" "+ycDevices.get(0).getLocation());
                                jsonObject.put("time", DateUtil.getNowTime());
                                log.info("addAlert === 4  sendMsg : "+ycDevices.get(0).getPhone());
                                smsUtils.sendMsg(phoness[i],jsonObject.toJSONString());
                            }
                        }

                    }
                }


            }

        }
    }


    /**
     * 每两分钟执行一次
     */
    //0 0/2 * * * ?
    @Scheduled(cron = "0 0/2 * * * ?")
    public void queryRealData(){
//        String url = "http://dust.0531yun.cn/api/data/getRealtimeData?deviceIds=40237247,40248645,40248663,40248665,40248677,40248717";
//        String token = redis.opsForValue().get("ycToken");
//        if (token == null){
//            getToken();
//        }else{
//            String result = YcRequestUtil.doYcGet(url,token);
//            ObjectMapper objectMapper = new ObjectMapper();
//            try {
//                YcRequestBean bean = objectMapper.readValue(result, YcRequestBean.class);
//                if (bean.getData()!=null){
//                    bean.getData().forEach(item ->{
//                        log.info("item deviceId : "+item.getDeviceId());
//                        addData(item);
//                    });
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }

    }

    private void addData(YcRequestBean.DataDTO item) {
        YcDeviceData ycDeviceData = new YcDeviceData();
        ycDeviceData.setNo(item.getDeviceId());
        ycDeviceData.setType(1);
        ycDeviceData.setPm10(item.getPm10());
        ycDeviceData.setPm25(item.getPm25());
        ycDeviceData.setNoise(item.getNoise());
        ycDeviceData.setTem(item.getTem());
        ycDeviceData.setHum(item.getHum());
        ycDeviceData.setWp(item.getWp());
        ycDeviceData.setWs(item.getWs());
        ycDeviceData.setWd8(item.getWd8());
        ycDeviceData.setWd360(item.getWd360());
        ycDeviceData.setTsp(item.getTsp());
        ycDeviceData.setAtm(item.getAtm());
        ycDeviceData.setLux(item.getLux());
        ycDeviceData.setCo(item.getCo());
        ycDeviceData.setSo2(item.getSo2());
        ycDeviceData.setNo2(item.getNo2());
        ycDeviceData.setO3(item.getO3());
        StringBuilder sb = new StringBuilder();
        String delimiter = "-";
        sb.append(item.getR1()).append(delimiter).
                append(item.getR2()).append(delimiter).
                append(item.getR3()).append(delimiter).
                append(item.getR4()).append(delimiter).
                append(item.getR5()).append(delimiter).
                append(item.getR6()).append(delimiter).
                append(item.getR7()).append(delimiter).
                append(item.getR8());
        ycDeviceData.setRs(sb.toString());
        if (item.getStatus().equals("online")){
            ycDeviceData.setCreatedTime(new Date());
            ycDeviceDataService.save(ycDeviceData);
        }
    }

}
